﻿#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    table=TD_PREFIX;
    manager=nullptr;

    QString userLand=Location::document + APP_ROOT;
    configFile=userLand + QString("/") + SP_CFG;

    updateCategories();
    loadPreference();
}

Widget::~Widget()
{
    savePreference();
    delete ui;
}

void Widget::updateCategories()
{
    if(ui->categories->count() != 0)
        ui->categories->clear();

    QStringList items=sp_getCategory(table);
    if(!items.isEmpty())
        ui->categories->addItems(items);
}

void Widget::updateTraits()
{
    if(selectCategory.isEmpty())
        return;

    if(ui->traits->count() != 0)
        ui->traits->clear();

    QStringList items=sp_getItemsByCategory("label",table,selectCategory);
    if(!items.isEmpty())
        ui->traits->addItems(items);
}

void Widget::loadPreference()
{
    if(QFile::exists(configFile))
    {
        QSettings cfg(configFile,QSettings::IniFormat);
        cfg.setIniCodec("UTF-8");
        int x=cfg.value("Location/x").toInt();
        int y=cfg.value("Location/y").toInt();
        x= (x>0?x:200);
        y= (y>0?y:100);
        move(x,y);

        QString category=cfg.value("Main/category").toString();
        if(!category.isEmpty())
            ui->categories->setCurrentText(category);

        QString trait=cfg.value("Main/trait").toString();
        if(!trait.isEmpty())
            ui->traits->setCurrentText(trait);
    }
}

void Widget::savePreference()
{
    QSettings cfg(configFile,QSettings::IniFormat);
    cfg.setIniCodec("UTF-8");
    cfg.setValue("Location/x",x());
    cfg.setValue("Location/y",y());

    if(!selectCategory.isEmpty())
        cfg.setValue("Main/category",selectCategory);

    if(!selectTrait.isEmpty())
        cfg.setValue("Main/trait",selectTrait);
}

void Widget::on_keyword_returnPressed()
{
    QString keyword=ui->keyword->text().trimmed();
    if(keyword.isEmpty())
        return;

    if(selectCategory.isEmpty() || selectTrait.isEmpty())
        return;

    QString prefix=sp_getItemByCategory("detail",table,
                                        selectCategory,
                                        selectTrait).toString();
    if(prefix.isEmpty())
        prefix=BAIDU_PREFIX;

    QString url=prefix + keyword;
    QDesktopServices::openUrl(QUrl(url));
}

void Widget::on_categories_currentTextChanged(const QString &category)
{
    selectCategory=category;
    updateTraits();
}

void Widget::on_traits_currentTextChanged(const QString &trait)
{
    selectTrait=trait;
}

void Widget::on_btn_manager_clicked()
{
    if(manager == nullptr)
        manager=new Manager(this);

    manager->move(this->x() + 100,100);
    manager->show();
}
